package com.example.lotterysystem.controller.handler;

import com.example.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description: 全局异常处理
 * User: Li_yizYa
 * Date: 2025/8/1
 * Time: 23:12
 */
@RestControllerAdvice // 可以捕获全局抛的异常，所有的异常都会进入这个类里面
public class GlobalExceptionHandler {

    @Autowired
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = ServiceException.class)
    public CommonResult<?> serviceException(ServiceException e) {
        // 打错误日志
        logger.error("ServiceException: ", e);
        // 构造错误结果
        return CommonResult.error(
                GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMsg());
    }

    @ExceptionHandler(value = ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e) {
        // 打错误日志
        logger.error("controllerException: ", e);
        // 构造错误结果
        return CommonResult.error(
                GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMsg());
    }

    /**
     * 不在控制范围内的异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> exception(Exception e) {
        // 打错误日志
        logger.error("exception: ", e);
        // 构造错误结果
        return CommonResult.error(
                GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }


}
